package com.hks.quart.utils;

import java.lang.reflect.Method;

import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.alibaba.fastjson.JSONObject;
import com.hks.common.core.util.StringUtils;
import com.hks.common.core.web.HttpStatus;
import com.hks.quart.entity.ScheduleJobBean;
import com.hks.quart.entity.ScheduleJobLogBean;
import com.hks.quart.service.ScheduleJobLogService;

/**
 * 定时器执行日志记录
 */
public class TaskJobLog extends QuartzJobBean {

    private static final Logger LOG = LoggerFactory.getLogger(TaskJobLog.class);

    @Override
    protected void executeInternal(JobExecutionContext context) {
        ScheduleJobBean jobBean = (ScheduleJobBean) context.getMergedJobDataMap().get(ScheduleJobBean.JOB_PARAM_KEY);
        ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtil
                .getBean("scheduleJobLogService");
        // 定时器日志记录
        ScheduleJobLogBean logBean = new ScheduleJobLogBean();
        logBean.setJobId(jobBean.getJobId());
        logBean.setBeanName(jobBean.getBeanName());
        logBean.setParams(jobBean.getParams());
        logBean.setQuartzName(jobBean.getQuartzName());
        long beginTime = System.currentTimeMillis();
        try {
            // 加载并执行定时器的 run 方法
            Object target = SpringContextUtil.getBean(jobBean.getBeanName());
            Method method = target.getClass().getDeclaredMethod("run", ScheduleJobBean.class);
            String result = (String) method.invoke(target, jobBean);
            long executeTime = System.currentTimeMillis() - beginTime;
            logBean.setTimes((int) executeTime);
            logBean.setResult(result);
            if (StringUtils.isEmpty(result)) {
                logBean.setStatus(1);
                logBean.setError("请求异常，接口访问失败！");
            } else {
                JSONObject jsonObject = JSONObject.parseObject(result);
                int code = jsonObject.getIntValue("code");
                String msg = jsonObject.getString("msg");
                if (HttpStatus.SUCCESS.getCode() == code) {
                    logBean.setStatus(0);
                    logBean.setResult(msg);
                } else {
                    logBean.setStatus(1);
                    logBean.setError(msg);
                }
            }
            String ret = logBean.getStatus() == 0 ? "成功" : "失败";
            LOG.info("定时器 === >> " + jobBean.getJobId() + "执行" + ret + "，耗时 === >> " + executeTime + "，结果为 === >> "
                    + result);
        } catch (Exception e) {
            // 异常信息
            long executeTime = System.currentTimeMillis() - beginTime;
            logBean.setTimes((int) executeTime);
            logBean.setStatus(1);
            logBean.setError(e.getMessage());
            LOG.info("定时器 === >> " + jobBean.getJobId() + "执行异常，Exception === >> " + e.getMessage());
        } finally {
            scheduleJobLogService.save(logBean);
        }
    }
}
